export default class Watcher {
    constructor(vm, sourceKey,cb) {
        this.vm = vm;
        this.cb = cb;
        this.getter = expOrFnc(sourceKey);
        this.value = this.get();
    }
    get() {
        window.target = this;
        const value = this.getter.call(this.vm, this.vm);
        window.target = undefined;
        return value;
    }
    update() {
        const value = this.value;
        this.value = this.get();
        this.cb.call(this.vm, value, this.value);
    }
}

function expOrFnc(sourceKey) {
    const regx = /^\w.$/;
    if (regx.test(sourceKey)) return;
    const attributes = sourceKey.split('.');
    return function(target) {
        let value = target;
        for (const key of attributes) {
            value = value[key];
            if (!value) return;
        }
        return value;
    }
}